package com.ticket.sass.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.sass.admin.mapper.CouponWeekMapper;
import com.ticket.sass.admin.service.BaseService;
import com.ticket.sass.common.entity.tenant.CouponWeekEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 优惠券可用周期表 服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-03-13
 */
@Service
public class CouponWeekServiceImpl extends ServiceImpl<CouponWeekMapper, CouponWeekEntity> implements BaseService<CouponWeekEntity> {
    
    public List<Integer> getWeeksByCouponId(Long couponId) {
        QueryWrapper<CouponWeekEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("coupon_id", couponId);
        queryWrapper.select("week");
        List<CouponWeekEntity> couponWeekList = this.baseMapper.selectList(queryWrapper);
        
        List<Integer> weeks = new ArrayList<>();
        for (CouponWeekEntity couponWeek : couponWeekList) {
            weeks.add(couponWeek.getWeek());
        }
        
        return weeks;
    }
    
    public List<CouponWeekEntity> listByCouponId(Long couponId) {
        List<CouponWeekEntity> weekEntities = this.baseMapper.selectList(new QueryWrapper<CouponWeekEntity>().eq("coupon_id", couponId));
        
        return weekEntities;
    }
    
    public Map<Long, List<CouponWeekEntity>> listByCouponIds(List<Long> couponIds) {
        if (couponIds.size() == 0){
            return new HashMap<>();
        }
       
        Map<Long, List<CouponWeekEntity>> result = new HashMap<>();
        
        // 查询所有符合条件的记录
        List<CouponWeekEntity> entities = this.baseMapper.selectList(
            new QueryWrapper<CouponWeekEntity>().in("coupon_id", couponIds)
        );
        
        // 遍历查询结果，将结果按照 coupon_id 分组
        for (CouponWeekEntity entity : entities) {
            Long couponId = entity.getCouponId();
            if (!result.containsKey(couponId)) {
                result.put(couponId, new ArrayList<>());
            }
            result.get(couponId).add(entity);
        }
        
        return result;
    }
    
}
